<?php
/**
 * 遍历某个目录下的所有文件
 * @param string $dir
 */
function scanAll($dir)
{
  $list = array();
  $list[] = $dir;

  while (count($list) > 0)
  {
    //弹出数组最后一个元素
    $file = array_pop($list);

    //处理当前文件
    echo basename($file)."\r\n" . "<br/>";


    //如果是目录
    if (is_dir($file))
    {
      $children = scandir($file);
      foreach ($children as $child)
      {
        if ($child !== '.' && $child !== '..')
        {
          $list[] = $file.'/'.$child;
        }
      }
    }
  }
}

// scanAll('E:\\Temp');

function file_list($dir,$pattern="")
{
  $arr=array();
  $dir_handle=opendir($dir);
  if($dir_handle)
  {
    while(($file=readdir($dir_handle))!==false)
    {
      if($file==='.' || $file==='..')
      {
        continue;
      }
      $tmp=realpath($dir.'/'.$file);
      if(is_dir($tmp))
      {
        $retArr=file_list($tmp,$pattern);
        if(!empty($retArr))
        {
          $arr[]=$retArr;
        }
      } else
      {
        if($pattern==="" || preg_match($pattern,$tmp))
        {
          $arr[]=$tmp;
        }
      }
    }
    closedir($dir_handle);
  }
  return $arr;
}
// var_dump(file_list("E:\\Temp\\Blog"));


$dir = 'E:\\Temp';

function recurDir($pathName) {
    $result = array();
    $temp = array();
    if( !is_dir($pathName) || !is_readable($pathName) ){
        return null;
    }
    $allFiles = scandir($pathName);
    foreach($allFiles as $fileName){
        if( in_array($fileName, array('.', '..')) ) continue;
        $fullName = $pathName . '/' . $fileName;
        if( is_dir($fullName) ){
            $result[$fileName] = recurDir($fullName);
        }else{
            $temp[] = $fileName;
        }
    }
    if($temp){
        foreach( $temp as $f ){
            $result[] = $f;
        }
    }

    return $result;
}

function bl($arr, $l = '-|'){
    static $l = '';
    static $str = '';
    foreach($arr as $key=>$val){
        if(is_array($arr[$key])){
            //echo $val . "<br>";
            //echo $l . $key . "<br>";
            $str .= $l . $key . "<br>";
            $l .= '-|';
            bl($arr[$key], $l);
        }else{
            //echo $l . $val . "<br>";
            $str .= $l . $val . "<br>";
        }
    }
    $l = '';
    return $str;
}

$tree = recurDir($dir);
// echo "<pre>";
// print_r($tree);
// echo "</pre>";
// echo "<br>------------------------------------------<br>";
$data = bl($tree);
echo "<pre>";
print_r($data);
echo "</pre>";